package com.luo.chengrui.datapermission.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.luo.chengrui.datapermission.interceptor.DataPermissionAnnotationAdvisor;
import com.luo.chengrui.datapermission.interceptor.DataPermissionSqlParserInterceptor;
import com.luo.chengrui.datapermission.rules.DataPermissionRule;
import com.luo.chengrui.datapermission.rules.DefaultDataPermissionRule;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Role;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 配置mybatisPlusInterceptor
 */
@AutoConfiguration
public class DataPermissionInterceptorConfiguration {

    @Bean
    @ConditionalOnMissingBean(value = {MybatisPlusInterceptor.class})
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        return new MybatisPlusInterceptor();
    }

    @Bean
    @ConditionalOnBean(value = {DataPermissionRule.class})
    public DataPermissionSqlParserInterceptor dataPermissionSqlParserInterceptor(MybatisPlusInterceptor mybatisPlusInterceptor, List<DataPermissionRule> dataPermissionRule) {
        //添加权限拦截器。
        DataPermissionSqlParserInterceptor inner = new DataPermissionSqlParserInterceptor(dataPermissionRule);
        List<InnerInterceptor> inners = new ArrayList<>(mybatisPlusInterceptor.getInterceptors());
        inners.add(0, inner);
        mybatisPlusInterceptor.setInterceptors(inners);
        return inner;
    }



    /**
     * 权限注解拦截器。
     *
     * @return
     */
    @Bean
    @Role(2)
    public DataPermissionAnnotationAdvisor dataPermissionAnnotationAdvisor() {
        return new DataPermissionAnnotationAdvisor();
    }

}
